package Day14;

import java.util.Iterator;

public class Demo04 {
    public static void main(String[] args) {
        ListNode<String> list = new ListNode<>();
        list.add("多多");
        list.add("稍稍");
        list.add("心心");
        list.add("微微");
        for (String s:list) {
            System.out.println(s);
        }
        String s = list.remove(0);
        System.out.println("删除的元素：" + s);



    }
}
class ListNode<T> implements Iterable<T>{//继承Iterable接口实现遍历
    private Node head;//首结点
    private int size;//链表长度

    private class Node {
        T item;//存储数据
        Node next;//结点

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    public ListNode(){
        //初始化头结点
        this.head = new Node(null,null);
        //初始化链表长度
        size = 0;
    }
    //清空链表
    public void clear(){
        head.next = null;
        this.size = 0;
    }

    //获取链表长度
    public int length(){
        return size;
    }

    //判断是否为空
    public boolean isEmpty(){
        return size == 0;
    }

    //获取指定位置i的元素
    public T get(int i){
        if(i <= size){
        Node n = head.next;
        for (int j = 0; j < i; j++) {
            n = n.next;
        }
        return n.item;
        }else {
            return null;
        }
    }

    //像链表中添加元素
    public void add(T t){
        Node n = head;
        while(n.next != null){
            n = n.next;
        }
        Node newNode = new Node(t,null);
        n.next = newNode;
        size++;
    }

    //指定位置添加元素
    public void insert(int i,T t){
        //找i位置前一个结点
        Node n = head;
        for (int j = 0; j < i - 1; j++) {
            n = n.next;
        }
        //找i位置节点
        Node curr = n.next;
        Node newNode = new Node(t,curr);
        n.next = newNode;
        size++;
    }

    //删除i下标的元素
    public T remove(int i){
        Node n = head;
        //找出i位置前一个节点
        for (int j = 0; j < i - 1; j++) {
            n = n.next;
        }
        //找出i位置后一个节点
        Node l = n.next;//i的节点
        n.next = l.next;
        size--;
        return l.item;
    }

    //查找元素第一出现的位置
    public int indexOf(T t){
        Node n = head;
        int i = -1;
        for (i = 0; i < size; i++) {
            n = n.next;
            if(n.item.equals(t)){
                return i;
            }
        }
        return i;
    }

    @Override
    public Iterator<T> iterator() {
        return new LIterator();
    }

    private class LIterator implements Iterator{
        private Node n;
        public LIterator(){
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }


}